<template>
  <view class="asset-pg">
    <u-navbar title="资产盘点" :autoBack="true" :placeholder="true">
      <view class="u-nav-slot" slot="right" v-if='showPrintCode'>
        <view class="print-box" @click="printQrcode">标签打印</view>
      </view>
    </u-navbar>

    <u--form :model="form" ref="uForm" :rules="rules" labelPosition="top" class="form-box" labelWidth="auto">

      <u-form-item label="资产分类" prop="assetType">
        <view class="select-item" @click="showAssetTypeModel">
          <text class="select-text">
            {{ form.assetTypeName || '请选择资产分类' }}
          </text>
          <u-icon name="arrow-right" size="18" color="#999" />
        </view>
      </u-form-item>

      <u-form-item label="条码编号">
        <u--input v-model="form.barcodeNumber" disabled />
      </u-form-item>

      <u-form-item label="资产名称" prop="title" >
        <u--input v-model="form.title" clearable  />
      </u-form-item>

      <u-form-item label="资产品牌" prop="brand" >
        <u--input v-model="form.brand" clearable  />
      </u-form-item>

      <u-form-item label="资产型号" prop="specificationModel" >
        <u--input v-model="form.specificationModel" clearable  />
      </u-form-item>

      <u-form-item label="资产数量" prop="number" >
        <u--input v-model="form.number" clearable />
      </u-form-item>

      <u-form-item label="成新率" prop="newnessRate" v-if="form.assetType=='JJ'">
        <!-- <u--input v-model="form.newnessRate" clearable /> -->
        <view class="select-item" @click="showNewnessRate = true">
          <text class="select-text">
            {{ form.newnessRateName || '请选择成新率' }}
          </text>
          <u-icon name="arrow-right" size="18" color="#999" />
        </view>
      </u-form-item>

      <u-form-item label="使用人" prop="useUserName">
        <view class="select-item" @click="showUserSelect = true">
          <text class="select-text">
            {{ form.useUserName || '请选择资产使用人' }}
          </text>
          <u-icon name="arrow-right" size="18" color="#999" />
        </view>
      </u-form-item>

      <u-form-item label="存放地点" prop="storageLocation">
        <u--input v-model="form.storageLocation" clearable />
      </u-form-item>

      <u-form-item label="业务状态" prop="businessStatus">
        <u-radio-group v-model="form.businessStatus">
          <u-radio v-for="(item, index) in businessStatus" :key="index" :name="item.value">
            {{ item.label }}
          </u-radio>
        </u-radio-group>
      </u-form-item>

      <u-form-item label="生产日期" prop="obtainTime">
        <view class="select-item" @click="showObtainTime = true">
          <text class="select-text">
            {{ form.obtainTime || '请选择生产日期' }}
          </text>
          <u-icon name="arrow-right" size="18" color="#999" />
        </view>
      </u-form-item>
	  <u-form-item label="备注" prop="remark">
		  <u--input v-model="form.remark" clearable />
      </u-form-item>

      <u-form-item label="资产图片">
        <u-upload @afterRead="afterRead" @delete="deletePic" :file-list="fileList" name="1" multiple
                  :maxCount="10" />
      </u-form-item>
    </u--form>

    <!-- 弹出选择资产分类 -->
    <u-action-sheet :show="showAssetType" mode="bottom" height="50%" :closeOnClickOverlay="true">
      <scroll-view style="height: 100%;" scroll-y>
        <view v-for="item in assetTypeList" :key="item.value" class="asset-type-item"
              @click="selectAssetType(item)">
          {{ item.label }}
        </view>
      </scroll-view>
    </u-action-sheet>

    <!-- 弹出选择成新率 -->
    <u-action-sheet :show="showNewnessRate" mode="bottom" height="50%" :closeOnClickOverlay="true">
      <scroll-view style="height: 100%;" scroll-y>
        <view v-for="item in newnessRateList" :key="item.value" class="asset-type-item"
              @click="selectNewnessRate(item)">
          {{ item.label }}
        </view>
      </scroll-view>
    </u-action-sheet>

    <!-- 弹出取得时间 -->
    <u-datetime-picker
        :minDate="308652145124"
        :show="showObtainTime"
        @confirm="handleObtainTime"
        :closeOnClickOverlay="true"
        @close="closeObtainTime"
        mode="date"
    ></u-datetime-picker>

    <!-- 选择使用人员 -->
    <u-popup :show="showUserSelect" mode="bottom" height="80%" :closeable="true" @close="showUserSelect=false">
      <view class="select-panel" style="margin-top: 40px;padding: 10px;">
        <view class="search-user-box">
          <u--input placeholder="请输入名字" clearable border="surround" v-model="searchUser"></u--input>
          <u-button @click="search" type="primary" text="搜索" style="width: 100px;margin-left: 10px;background-color: deepskyblue;"></u-button>
        </view>
        <view>
          <scroll-view style="height: 800rpx" scroll-y>
            <view v-for="item in userList" :key="item.id" class="asset-type-item"
                  @click="handleUseUser(item)">
              {{item.deptName}}-{{ item.nickname }}
            </view>
          </scroll-view>
        </view>
      </view>
    </u-popup>

    <view class="footer-box" v-if="!submitFinalStatus">
      <view class="save-btn" @click="submit">{{edit?'修改':'保存'}}数据</view>
    </view>

    <ble-print ref="blePrintRef" v-if='showPrintCode'></ble-print>

  </view>
</template>

<script>
import {
  getDictListAllSimple
} from '@/api/dict/index.js'
import {
  getBarcodeNumber,
  uploadFile,
  assetCreate,
  assetUpdate,
  getDetailByBarcodeNumber
} from '@/api/asset/index.js'
import {
  getUserPage
} from '@/api/system/user.js'
import dayjs from 'dayjs'
import BlePrint from '@/components/ble-print/index.vue'
export default {
  data() {
    return {
      edit:false,
      edit_copy:false,
      searchUser: '',
      fileList: [],
      submitFinalStatus:false,
      form: {
        barcodeNumber: '',
        title: '',
        assetType: '',
        brand: '',
        remark: '',
        assetTypeName: '',
        number: '',
        useDept: '',
        specificationModel: '',
        newnessRate: '',
        newnessRateName: '',
        obtainTime: "",
        useUser: '',
        useUserName: '',
        storageLocation: uni.getStorageSync("input_storageLocation") || "",
        businessStatus: '',
      },
      businessStatus: [],
      assetTypeList: [],
      newnessRateList: [],
      showNewnessRate: false,
      showAssetType: false,
      showObtainTime: false,
      showPrintCode: false,
      showUserSelect: false,
      rules: {
        barcodeNumber: [{
          required: true,
          message: '条码不能为空',
          trigger: ['blur']
        }],
        title: [{
          required: true,
          message: '资产名称不能为空',
          trigger: ['blur']
        }],
        brand: [{
          required: true,
          message: '资产品牌不能为空',
          trigger: ['blur']
        }],
        specificationModel: [{
          required: true,
          message: '资产型号不能为空',
          trigger: ['blur']
        }],
        number: [{
          required: true,
          message: '资产数量不能为空',
          trigger: ['blur']
        }],
        assetType: [{
          required: true,
          message: '资产分类不能为空',
          trigger: ['blur']
        }],
        useUser: [{
          required: true,
          message: '使用人不能为空',
          trigger: ['blur']
        }],
        storageLocation: [{
          required: true,
          message: '存放地点不能为空',
          trigger: ['blur']
        }],
        businessStatus: [{
          required: true,
          message: '业务状态不能为空',
          trigger: ['blur']
        }],
      },
      selectedCompany: '',
      selectedDept: '',
      companyList: [],
      departmentList: [],
      allUserList: [],
      userList: [], // 当前筛选后显示的人员列表
    }
  },
  components: {
    BlePrint
  },
  watch: {
    'form.obtainTime': {
      handler:function (v){
        if(!v){
          return
        }
        this.form.obtainTime = dayjs(v).format("YYYY-MM-DD")
      },
      deep:true
    },
    'form.assetType': function(v) {
      if(this.edit) {
        return
      }
      this.getBarcodeNumber()
      if(v=="JJ"){
        this.$refs.uForm.setRules({...this.rules,newnessRate: [{
            required: true,
            message: '成新率不能为空',
            trigger: ['blur']
          }],})
      }else{
        this.form.newnessRate=""
        this.$refs.uForm.setRules(this.rules)
      }
    },
    'form.storageLocation':function(v){
      uni.setStorageSync("input_storageLocation",v)
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    async init(){
      await this.getDictList()
      await this.getUserList()
      const edit_barcodeNumber = uni.getStorageSync("edit_barcodeNumber")
      if(edit_barcodeNumber){
        this.getDetailByBarcodeNumber(edit_barcodeNumber)
      }
    },
    showAssetTypeModel(){
      if(this.edit){
        uni.showToast({
          icon:'none',
          title:"不能修改资产分类!"
        })
        return
      }
      this.showAssetType = true
    },
    async getDetailByBarcodeNumber(edit_barcodeNumber){
      const ret = await getDetailByBarcodeNumber(edit_barcodeNumber)
      if(ret.data) {
        const {files,obtainTime,number,createTime,...other} = ret.data
        this.form = other
		const edit_copy = uni.getStorageSync("edit_copy")
		this.edit_copy = edit_copy
		if(!edit_copy) {
			if(files){
			  this.fileList = JSON.parse(files)
			}
			this.edit = true
		}else{
			this.form.id = null
		}
        if(obtainTime){
          this.form.obtainTime = dayjs(obtainTime).format("YYYY-MM-DD")+""
        }
        this.form.number = number+""
        if(other.assetType){
          const itemAssetType = this.assetTypeList.find(v=>v.value==other.assetType)
          if(itemAssetType){
            this.form.assetTypeName = itemAssetType.label
          }
        }
        if(other.newnessRate){
          const itemAssetType = this.newnessRateList.find(v=>v.value==other.newnessRate)
          if(itemAssetType){
            this.form.newnessRateName = itemAssetType.label
          }
        }
      }else{
        uni.showToast({
          title:edit_barcodeNumber+"数据不存在!",
          icon:'none'
        })
      }
    },
    search(){
      const u = this.allUserList.filter(v=>`${v.deptName}-${v.nickname}`.includes(this.searchUser))
      this.userList = u
    },
    async getUserList() {
      const ret = await getUserPage({
        pageSize: 10000
      })
      const list = ret.data.list || []
      this.allUserList = list
      this.userList = list
    },
    async getDictList() {
      const ret = await getDictListAllSimple()
      const dictData = ret.data || []
      // 业务状态
      const businessStatus = dictData.filter(v => v.dictType === 'business_status')
      this.businessStatus = businessStatus
      // 资产分类
      const assetTypeList = dictData.filter(v => v.dictType === 'asset_classification')
      this.assetTypeList = assetTypeList
      // 成新率
      const newnessRateList = dictData.filter(v => v.dictType === 'newness_rate')
      this.newnessRateList = newnessRateList
    },
    selectAssetType(item) {
      this.form.assetType = item.value
      this.form.assetTypeName = item.label
      this.showAssetType = false
    },
    selectNewnessRate(item) {
      this.form.newnessRate = item.value
      this.form.newnessRateName = item.label
      this.showNewnessRate = false
    },
    async getBarcodeNumber() {
      const ret = await getBarcodeNumber(this.form.assetType)
      this.form.barcodeNumber = ret.data
    },
    handleObtainTime(e){
      const {value} = e
      if(value) {
        this.form.obtainTime = dayjs(value).format("YYYY-MM-DD")
      }
      this.showObtainTime = false
    },
    closeObtainTime(e){
      this.showObtainTime = false
    },
    handleAsset(e, a) {
      const {
        label,
        value
      } = e[0]
      this.form.assetType = value
      this.form.assetTypeName = label
    },
    handleUseUser(e) {
      const {
        deptName,
        nickname,
        deptId,
        postIds,
        mobile,
        id
      } = e
      this.form.useUserName = nickname
      this.form.useUser = id
	  this.form.useDept = deptId
      this.showUserSelect = false
    },
    printQrcode() {
      const tenant = uni.getStorageSync("active_tenant")
      const tenantName = tenant.name
      // const useName = "梅红"
      // const assetName = "戴尔电脑"
      // const storageLocation = "东楼1205"
      // const barcodeNumber = "TY20250608122540"
      this.$refs.blePrintRef.printQrcode({
        tenantName,
        assetName:this.form.title,
		assetNumber:this.form.assetNumber,
        useName: this.form.useUserName,
        storageLocation: this.form.storageLocation,
        barcodeNumber: this.form.barcodeNumber
      })
    },
    async submit() {
      try {
        const valid = await this.$refs.uForm.validate()
        if (valid) {
          if (this.fileList && this.fileList.length){
            const isHttp = this.fileList.some(v=>(v.url+"").includes("http"));
            if(!isHttp){
              uni.showToast({
                title:"图片上传中，或者请重新上传!",
                icon:"none"
              })
              return
            }
          }
          const files = JSON.stringify(this.fileList.map(v=>{
            const {url,name,size} =v
            return {
              url,name,size
            }
          }))
          const api = this.edit?assetUpdate:assetCreate
          const ret = await api({
            ...this.form,
            files
          })
          uni.showToast({
            title: this.edit?'修改成功':'新增成功',
            icon: 'success'
          })
		  uni.setStorageSync("refresh",true)
          this.submitFinalStatus = true
          this.showPrintCode = true
        }
      } catch (err) {
        console.log('验证失败', err)
      }
    },
    // 删除图片
    deletePic(event) {
      this[`fileList`].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList`].length;
      lists.map((item) => {
        this[`fileList`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList`][fileListLen];
        this[`fileList`].splice(
            fileListLen,
            1,
            Object.assign(item, {
              status: "success",
              message: "",
              url: result,
            })
        );
        fileListLen++;
      }
    },
    async uploadFilePromise(url) {
      const ret = await uploadFile({
        name: 'file',
        filePath: url
      })
      return ret.data
    },
  },
}
</script>

<style lang="scss" scoped>
@import "@/uni_modules/uview-ui/index.scss";
::v-deep .u-input{
  border-width:1px !important;
  border-color:#dadbde !important;
}
.asset-pg {
  background-color: #fff;
  padding: 20rpx;

  .form-box {
    margin-bottom: 120rpx;
  }

  .print-box {
    margin-right: 10px;
    color: #fff;
    background-color: #ff842c;
    border-radius: 4px;
    padding: 6rpx 12rpx;
  }

  .footer-box {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100rpx;
    background-color: #fff;
    border-top: 1px solid #eee;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;
    .save-btn {
      width: 80%;
      background-color: #2cabff;
      color: #fff;
      padding: 20rpx;
      text-align: center;
      border-radius: 12rpx;
    }
  }

  .asset-type-item {
    padding: 30rpx;
    border-bottom: 1px solid #eee;
    font-size: 30rpx;
  }

  .select-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12rpx 20rpx;
    border: 1px solid #e5e5e5;
    border-radius: 8rpx;
    background-color: #fff;
    color: #333;
    width: 100%;
    height: 40px;
  }

  .select-text {
    flex: 1;
    color: #333;
  }

  .search-user-box {
    display: flex;
  }
}
::v-deep .u-navbar--fixed{
	box-shadow:0 1px 10px rgba(0, 0, 0, 0.16);
}
</style>
